#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/un.h>
#include <stdint.h>
#include <errno.h>
#include <unistd.h>
#define local_socket_path "/tmp/mylocal.socket"

int createLocalListenSocket()
{
    int                sockfd = 0;
    struct sockaddr_un servaddr;
    memset(&servaddr, 0, sizeof(servaddr));

    if((sockfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
        printf("%s\n", "socket create failed.");
        return -1;
    }

    servaddr.sun_family = AF_UNIX;
    strcpy(servaddr.sun_path, local_socket_path);
    unlink(local_socket_path);
    int len =
        (offsetof(struct sockaddr_un, sun_path) + strlen(servaddr.sun_path));
    if(bind(sockfd, (struct sockaddr*)&servaddr, len)) {
        printf("bind local socket failed\n");
        return -2;
    }

    if(listen(sockfd, 10)) {
        printf("local socket listen failed\n");
        return -3;
    }
    return sockfd;
}

int createLocalConnectSocket()
{
    int connectfd = socket(PF_UNIX, SOCK_STREAM, 0);
    if(-1 == connectfd) {
        printf("close local connect socket failed\n");
        return -1;
    }

    struct sockaddr_un cliaddr;
    cliaddr.sun_family = AF_UNIX;
    strcpy(cliaddr.sun_path, local_socket_path);
    // int len = sizeof(cliaddr);
    int len =
        (offsetof(struct sockaddr_un, sun_path) + strlen(cliaddr.sun_path));
    if(connect(connectfd, (struct sockaddr*)&cliaddr, len)) {
        printf("local socket connect failed\n");
        return -2;
    }

    printf("local socket connect success\n");
    return connectfd;
}
